package edu.gatech.cs4400.spring2014.A8.view;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import edu.gatech.cs4400.spring2014.A8.control.WaitedOn;

/**
 * JPanel used to enter login information or to navigate to new user registration.
 * 
 * @author Stephen
 */
public class LoginPanel extends JPanel implements ActionListener, WaitedOn {
	public static enum Feedback{LOGIN, REGISTER};
	private static final long serialVersionUID = 1L;
	
	public boolean finished;
	public Feedback feedback;
	
	private JPanel innerPanel;
	private JTextField usernamebox;
	private JTextField passwordbox;
	private JButton submitbutton;
	private JButton registerbutton;
	private JLabel messagelabel;
	
	/**
	 * Constructor. Set up the panel's components
	 */
	public LoginPanel() {
		finished = false;
		
		usernamebox = new JTextField(20);
		passwordbox = new JTextField(20);
		submitbutton = new JButton("Login");
		registerbutton = new JButton("Register New Account");
		messagelabel = new JLabel("");
		
		submitbutton.addActionListener(this);
		registerbutton.addActionListener(this);
		
		innerPanel = new JPanel();
		innerPanel.setLayout(new GridLayout(5,1));
		innerPanel.add(usernamebox);
		innerPanel.add(passwordbox);
		innerPanel.add(submitbutton);
		innerPanel.add(registerbutton);
		innerPanel.add(messagelabel);
		this.add(innerPanel);
	}
	
	/**
	 * Can be called after user input to reset flags
	 * Used whenever the panel needs to be waited on again
	 */
	public void reset() {
		finished = false;
		feedback = null;
		messagelabel.setText("");
	}
	
	/**
	 * Set the message on the panel
	 * @param message Message to display
	 */
	public void setMessage(String message) {
		messagelabel.setText(message);
	}
	
	/**
	 * Get the input username
	 * @return text from the username box
	 */
	public String getUsername() {
		return usernamebox.getText();
	}
	
	/**
	 * Get the input password
	 * @return text from the password box
	 */
	public String getPassword() {
		return passwordbox.getText();
	}

	/**
	 * Interpret button presses
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		finished = true;
		if (arg0.getSource().equals(submitbutton)) {
			feedback = Feedback.LOGIN;
		}
		else {
			feedback = Feedback.REGISTER;
		}
		synchronized (this) {
			this.notify();
		}
	}

	@Override
	public boolean isDone() {
		return finished;
	}
}
